// 导入：类型、接口、模块、组件、样式
import { Component } from "react";
import { random } from "../../utils";

import styled from "./styled.module.scss"; // FIXED: 存在样式污染后期优化

console.log("login");

class Index extends Component {
  state = {
    formData: {
      mobile: "",
      password: "",
    },
  };

  onUpdateForm = (e: React.ChangeEvent<HTMLInputElement>) => {
    this.setState({
      formData: {
        ...this.state.formData,
        [e.target.name]: e.target.value,
      },
    });
  };

  componentDidMount(): void {
    // console.log(document.querySelector("#mobile"));
    // console.log(this.refs.mobile);
    (this.refs.mobile as HTMLInputElement).focus();
  }

  // # 短信倒计时
  // - 1 给按钮加ref 后期修改文字、按钮禁用等
  // - 2 绑定点击事件，事件处理函数中
  //   - 2.1 验证手机号
  //   - 2.2 -1
  //   - 2.3 每个1s -1
  // - 3 请求接口 后续做

  onSendSms = () => {
    // - 1 给按钮加ref 后期修改文字、按钮禁用等
    // - 2 绑定点击事件，事件处理函数中
    const { mobile } = this.state.formData;
    //   - 2.1 验证手机号
    if (!/^1\d{10}$/.test(mobile)) {
      alert("手机号有误");
      return;
    }
    //   - 2.2 -1       定时time 10s、-1、修改文字、禁用
    let time: number = 10;
    time--;
    (this.refs.sms as HTMLButtonElement).innerText = `剩余${time}s`;
    (this.refs.sms as HTMLButtonElement).disabled = true;
    //   - 2.3 每个1s -1
    let t = setInterval(() => {
      if (time <= 1) {
        // 清除定时器
        clearInterval(t);
        // 数据归位
        time = 10;
        (this.refs.sms as HTMLButtonElement).innerText = `获取验证码`;
        (this.refs.sms as HTMLButtonElement).disabled = false;
        return;
      }
      time--;
      (this.refs.sms as HTMLButtonElement).innerText = `剩余${time}s`;
      // (this.refs.sms as HTMLButtonElement).disabled = true;
    }, 5000);
    // - 3 请求接口 后续做
    console.log("请求接口");
  };

  render() {
    const { mobile, password } = this.state.formData;
    const logoName = random(1, 2);
    return (
      <div className={styled.login}>
        {/* <h1>登录页</h1> */}
        {/* <img src={require("../../assets/logo1.jpg")} alt="logo" width={300} /> */}
        <img
          src={require(`../../assets/logo${logoName}.jpg`)}
          alt="logo"
          width={300}
          height={168}
        />
        <input
          id="mobile"
          ref="mobile"
          type="text"
          placeholder="手机号"
          value={mobile}
          name="mobile"
          onChange={this.onUpdateForm}
        />
        <input
          type="text"
          placeholder="验证码"
          value={password}
          name="password"
          onChange={this.onUpdateForm}
        />
        <button className={styled.submit}>登录</button>
        <p>收不到验证码</p>
        <button className={styled.code} ref="sms" onClick={this.onSendSms}>
          获取验证码
        </button>
      </div>
    );
  }
}
export default Index;
